﻿var pageNum = 0;
var drawLocked = false;
var docObject;
var wisId = GetQueryString("wisid");
var dmsPubKey = "pub_9c3738b837670f266e4cac940cf505f1";
var dmsSubKey = "sub_5f8fa66f7a46cd7c2274a4e04c15d576";



function GetQueryString(param) {
    var request = {
        QueryString: function (val) {
            var uri = window.location.search;
            var re = new RegExp("" + val + "=([^&?]*)", "ig");
            return ((uri.match(re)) ? (decodeURI(uri.match(re)[0].substr(val.length + 1))) : '');
        }
    }
    return request.QueryString(param);
}

var userid = GetQueryString("userid");
var classid = GetQueryString("classid");

var topic_msg = GetQueryString("topic");
var topic_ctrl = GetQueryString("topic")+"_ctrl";
var topic_stu = GetQueryString("topic")+"_stu";
var topic_stu_refresh = GetQueryString("topic")+"_stu_refresh";
var online_count = 0;
var handerStuid = "";
var handerStuname = "";
/****************WIS相关*****************/

function getList(option){
   if(!classid){
	   alert("课堂数据未初始化");
	   return;
   }
   $.ajax({ 
        type:"POST",
        timeout:3000,
        url:"./remoteinvoke.php", 
        dataType:"json",
        data:{method:'getClassDocs',classid:classid},
        success: function(data){
            if(data.Flag == 100){
                if(option.success)option.success(data.Info);
            }else{
                if(option.failure)option.failure(data.FlagString);
            }
        },
        error:option.failure
    });
}

function loadDocList(  err ) {
    if(err != null){
        alert(err);
    }
    $(".docUploader img").remove();
    $(".docUploader a").show();
    $("#uploadForm").attr("src","uploadForm.html");
    getList({
        success: function (data) {
            console.log(data.result);
            var list = data.result;
            $("#docList").html("");
            for (var i = 0; i < list.length; i++) {
                var itemHtml = "<div docId='" + list[i]["docid"] + "'><span>" +
                    jQuery('<div />').text(decodeURIComponent(list[i].docname)).html() + "</span></div>";
                $("#docList").append(itemHtml);
            }
            if (!!docObject) {
                $("#docList div[docId=" + docObject["id"] + "]").addClass("selectDoc");
                $("#docList div[docId=" + docObject["id"] + "]").siblings().removeClass("selectDoc");
            }
            $("#docList div,#docList div span").click(function () {
                WIS.ChoseDoc({
                    docId: $(this).parent().attr("docId"),
                    failure: function () {
                        //alert("文档不存在!");
                        loadDocList();
                    }
                });
            });
            
        },
        failure: function (errStr) {
            alert(errStr.responseText);
        }
    });
}

function getQueryStr(str) {
    var LocString = String(window.document.location.href);
    var rs = new RegExp("(^|)" + str + "=([^&]*)(&|$)", "gi").exec(LocString), tmp;
    if (tmp = rs) {
        return tmp[2];
    }      
    return "";
}
$(function () {
    $(".colorList .toolItem").click(function () {
        WIS.Color($(this).attr("data-color"));
    });
    $(".lineList .toolItem").click(function () {
        WIS.LineWidth($(this).attr("data-line"));
    });
    $(".toolList .toolItem").click(function () {
        if ($(this).attr("data-cmd") == "Clear") {
            //WIS.Clear();
        	WIS.SetDrawType("clear");
        } else {
            WIS.SetDrawType($(this).attr("data-type"));
        }
    });
    $("#pageList").change(function (val) {
        WIS.ToPage($("#pageList").val());
    });
    $("#lockTool").click(function (e) {
        drawLocked = !drawLocked;
        WIS.AllowDraw({ballow:!drawLocked});
    });

    
    var api = WISAPI.New('./interface.php')
    WIS.Init({
        wisId: wisId,
        api: api,
        container: 'wis_context',
        width: 784,
        height: 550,
        success:function(){
            WIS.Color("#FF8C00");
            WIS.AllowDraw({ballow:true});
            
            if(WIS.GetCurrentDoc() == "" || WIS.GetCurrentDoc() == null){
                alert("请选择文档")
            }
        },
        failure:function(err){
           alert("init fail:  "+JSON.stringify(err));
        },
        updateUser:function(total){
        	if(total < online_count){
        		//setTimeout(function(){
        			//refreshUser();
        		//},1000);
        	}
            $(".rightLabel span").html(total);
            online_count = total;
        },
        onConnect:function(){

        },
        onReconnect:function(){

        },
        onConnectClose:function(){
           
        },
        onDocLoad: function (info) {
            console.log("docObject:"+JSON.stringify(info));
            docObject = info;
            if (!!docObject) {
            	$("#docList div[docId=" + docObject["id"] + "]").addClass("selectDoc");
            	$("#docList div[docId=" + docObject["id"] + "]").siblings().removeClass("selectDoc");
            }
            /*
            setTimeout(function(){
            	WIS.Resize(784,1000);
            },1000);
			*/
        },
        onPageChange:function(page,total){
            pageNum = total;
            $("#pageList").html("");
            for (var i = 1; i <= total; i++) {
                var option = $("<option>").val(i).text(i);
                $("#pageList").append(option);
            }
            $("#pageList").val(page);
        }
    });
    loadDocList();
});
/****************DMS相关*****************/

var userName = GetQueryString("name");
if (userName == null || userName.length == 0) userName = "匿名";

function AddMessage( name, msg, style) {
    var faceMsg = msg;
    for (var item in faceMap) {
        faceMsg = faceMsg.replace(new RegExp("\\"+item, "g"), "<img src='images/faces/" + faceMap[item] + ".gif'/>");
    }
    var msgHtml = "<div><span class='" + style + "' >" + name + "：</span>" + faceMsg + "</div>";
    $("#messageBox").html($("#messageBox").html() + msgHtml);
    $("#messageBox").scrollTop(document.getElementById("messageBox").scrollHeight);
};
function Publish() {
    var send = $("#msgSendTxt").val();
    if (send == "") return;
    send = jQuery('<div />').text(send).html();
    ROP.Publish('{  "name":"'+ userName+'", "message": "'+send +'"}', topic_msg);
    $("#msgSendTxt").val("");
};
ROP.On("enter_suc",
function () {
    AddMessage("系统消息", "连接成功", "sysSpan");
    refreshUser();
    pubStuEnterMsg();
});
ROP.On("reconnect",
function () {
    AddMessage("系统消息", "重新连接", "sysSpan");
});
ROP.On("offline",
function (err) {
    AddMessage("系统消息", "连接已断开", "sysSpan");
});
ROP.On("enter_fail",
function (err) {
    AddMessage("系统消息", "连接失败", "sysSpan");
});
ROP.On("losed",
function () {
    AddMessage("系统消息", "连接已断开", "sysSpan");
});
ROP.On("publish_data",
function (data, topic) {
    //console.log(data);
    var d = eval('(' + data + ')');
    if(topic == topic_msg){
    	var msg = d["message"];
    	if (msg != null) {
    		AddMessage( (!!d["name"]) ? d["name"] : "匿名", msg);
    	}
    }
    if(topic == topic_stu){
    	handleStuMsg(d);
    }
    if(topic == topic_stu_refresh){
    	handleStuRefresh(d);
    }
    if(topic == topic_ctrl){
    	handleCtrlMsg(d);
    }
    
});

function pubStuEnterMsg(){
	//如果是学生端，则发送进入消息
    setTimeout(function(){
    	if(terminal == "student"){
    		ROP.Publish('{"name":"'+ userName+'", "userid": "'+ userid +'","status":"enter"}', topic_stu);
        }
    },500);
}

function pubStuOutMsg(){
	//如果是学生端，则发送退出消息
    setTimeout(function(){
    	if(terminal == "student"){
    		ROP.Publish('{"name":"'+ userName+'", "userid": "'+ userid +'","status":"out"}', topic_stu);
        }
    },500);
}

function refreshUser(){
	//刷新用户列表topic_stu_refresh
	setTimeout(function(){
		if(terminal == "teacher"){
			$("#stuList").empty();
			ROP.Publish('{"oper":"refresh"}', topic_stu_refresh);
		}
	},1000);
}

function handleStuRefresh(refreshMsg){
	
    if(terminal == "student"){
		if(refreshMsg['oper'] == 'refresh'){
			ROP.Publish('{"name":"'+ userName+'", "userid": "'+ userid +'","status":"enter"}', topic_stu);
		}
	}
}

function handleStuMsg(stuMsg){
	//如果是老师端，则接收学生进入消息，并加入学生列表,退出则去除
	if(terminal == "teacher"){
		if(stuMsg["status"] == "enter"){
			var itemHtml = "<div stuId='" + stuMsg["userid"] + "'><span>" +stuMsg["name"]+ "</span><a>请回答</a></div>";
			var flag = false;
			$("#stuList div").each(function(index,element){
				var stuId = $(this).attr("stuId");
				if(stuId == stuMsg["userid"]){
					flag = true;
				}
			});
			if(!flag) {
				$("#stuList").append(itemHtml);
				$("#stuList div a").click(function () {
			        //点名回答
					if(terminal == "teacher"){
			    		handerStuid = $(this).parent().attr("stuId");
			    		handerStuname = $(this).parent().children("span:last").html();
			    		if(!handerStuid){
			    			alert("请选择一个学生");
			    			return;
			    		}
			    		ROP.Publish('{"name":"'+ handerStuname+'", "userid": "'+ handerStuid +'","oper":"puthand"}', topic_ctrl);
			    	}
			    });
			}
			
		}
		
	}
}

function handleCtrlMsg(ctrlMsg){
	if(terminal == "student"){
		if(ctrlMsg["oper"] == "canhand"){
			$("#canhand").attr("class","offMicBtn");
		}
		if(ctrlMsg["oper"] == "cannothand"){
			$("#canhand").attr("class","offHandBtn");
		}
		if(ctrlMsg["oper"] == "puthand"){
			handerStuname = ctrlMsg["name"];
			handerStuid = ctrlMsg["userid"];
			if(userid == ctrlMsg["userid"]){
				closeStuPlayHtml();
				openStuPublishHtml();
			}else{
				closeStuPublishHtml();
				openStuPlayHtml();
			}
		}
		if(ctrlMsg["oper"] == "closeStuPlay"){
			closeStuPublishHtml();
			closeStuPlayHtml();
		}
	}
	if(terminal == "teacher"){
		if(ctrlMsg["oper"] == "stuhand"){
			var itemHtml = "<div handId='" + ctrlMsg["userid"] + "'><span>" +ctrlMsg["name"]+ "</span><a>请回答</a></div>";
			var flag = false;
			$("#handList div").each(function(index,element){
				var stuId = $(this).attr("stuId");
				if(stuId == ctrlMsg["userid"]){
					flag = true;
				}
			});
			if(!flag) $("#handList").append(itemHtml);
			$("#handList div a").click(function () {
		        //举手点名回答
		    	if(terminal == "teacher"){
		    		handerStuid = $(this).parent().attr("handId");
		    		handerStuname = $(this).parent().children("span:last").html();
		    		if(!handerStuid){
		    			alert("请选择一个学生");
		    			return;
		    		}
		    		ROP.Publish('{"name":"'+ handerStuname+'", "userid": "'+ handerStuid +'","oper":"puthand"}', topic_ctrl);
		    	}
		    });
		}
		if(ctrlMsg["oper"] == "puthand"){
			handerStuname = ctrlMsg["name"];
			handerStuid = ctrlMsg["userid"];
			openStuPlayHtml();
		}
	}
}

function openStuPlayHtml(){
	$("#vadioPlay").show();
	$("#stuinfo").html(handerStuname+"正在视频中");
	$("#stuPlay").attr("src","stu_play.html?lssapp_id="+lssapp_id+"&stream_stu="+stream_stu);
}

function closeStuPlayHtml(){
	try{
		$(window.parent.document).contents().find("#stuPlay")[0].contentWindow.closeme(); 
	}catch(err){}
	$("#stuPlay").attr("src","");
	$("#vadioPlay").hide();
}

function openStuPublishHtml(){
	$("#vadioPublish").show();
	$("#stupublish").show();
	$("#stuinfo_publish").html(handerStuname+"正在视频中");
	$("#stuPublish").attr("src","stu_publish.html?lssapp_id="+lssapp_id+"&stream_stu="+stream_stu);
}

function closeStuPublishHtml(){
	try{
		$("#stupublish").html("上麦");
		$(window.parent.document).contents().find("#stuPublish")[0].contentWindow.closeme(); 
	}catch(err){}
	$("#stuPublish").attr("src","");
	$("#vadioPublish").hide();
}


$(function () {
    ROP.Enter(dmsPubKey,dmsSubKey);
    ROP.Subscribe(topic_msg);
    ROP.Subscribe(topic_stu);
    ROP.Subscribe(topic_stu_refresh);
    ROP.Subscribe(topic_ctrl);
    document.onkeydown = function (e) {
        if (e == null || e.keyCode == null || e.ctrlKey == null) return;
        if (e.keyCode == 13 && e.ctrlKey) {
            document.getElementById("msgSendTxt").value += "\n";
        } else if (e.keyCode == 13) {
            e.preventDefault();
            Publish();
        }
    };
    
});